package cn.net.autocode.platform.datasource;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.utils.TreeUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.SqlWrapper;
import cn.net.autocode.dbManager.SqlWrapperBuilder;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@AutoCodeQuery(value="platformRole",description="角色相关查询")
public class PlatFormRoleDS {
    private final Dao dao;

    public PlatFormRoleDS(Dao dao) {
        this.dao = dao;
    }

    @AutoCodeQuery(value="publicRole",description="查询所有的公共角色")
    public JSONArray publicRole(JSONObject param) {
        return dao.queryJSONArray("select * from sys_roles where is_public = 'Y' order by label");
    }


    @AutoCodeQuery(value = "publicRoleMenus", description = "查询公共角色授权的菜单")
    public JSONObject publicRoleMenus(JSONObject param){
        JSONArray menus = dao.queryJSONArray("select * from sys_menus order by sort_no");
        JSONArray menusTree = TreeUtils.commonTree(menus);

        List<String> defaultCheckedKeys = dao.queryListValue("select menu_id from sys_role_menus where role_id=?",String.class,param.getString("roleId"));

        JSONObject rs = new JSONObject();
        rs.put("data",menusTree);
        rs.put("defaultCheckedKeys",defaultCheckedKeys);

        return rs;
    }

    @AutoCodeQuery(value = "publicRoleAppMenus", description = "查询公共角色授权的菜单")
    public JSONObject publicRoleAppMenus(JSONObject param){
        JSONArray menus = dao.queryJSONArray("select * from app_menus order by sort_no");
        JSONArray menusTree = TreeUtils.commonTree(menus);

        List<String> defaultCheckedKeys = dao.queryListValue("select menu_id from app_role_menus where role_id=?",String.class,param.getString("roleId"));

        JSONObject rs = new JSONObject();
        rs.put("data",menusTree);
        rs.put("defaultCheckedKeys",defaultCheckedKeys);

        return rs;
    }

    @AutoCodeQuery(value = "roles", description = "查询公共角色及组织机构下的角色信息")
    public JSONArray roles(JSONObject param) {
        String orgCode = UserThreadLocalUtils.getOrgCode();
        return dao.queryJSONArray("select * from sys_roles where is_public = 'Y' or org_code=? order by is_public desc,label",orgCode);
    }

    @AutoCodeQuery(value = "roleMenus", description = "查询组织角色授权的菜单信息")
    public JSONObject roleMenus(JSONObject param){

        String orgCode = UserThreadLocalUtils.getOrgCode();
        String roleId = param.getString("roleId");

        //判定一个角色是否为公共角色
        String isPublic = dao.queryValue("select is_public from sys_roles where id=?",String.class,roleId);

        //获取菜单信息
        List<String> menuIds = dao.queryListValue("select distinct menu_id from sys_organ_menu where org_code=?",String.class,orgCode);
        List<String> publicMenuIds = dao.queryListValue("select distinct id from sys_menus where is_public='Y'",String.class);

        menuIds.addAll(publicMenuIds);

        //获取父级id及爷爷级ID
        if (!menuIds.isEmpty()){
            String parentSql = "select distinct parent_id from sys_menus where id in (?)  or id in (select parent_id from sys_menus t2 where t2.id in (?))";
            List<String> parentIds = dao.queryListValue(parentSql,String.class,menuIds,menuIds);
            menuIds.addAll(parentIds);
        }

        JSONArray menus = new JSONArray();
        if (!menuIds.isEmpty()) {
            if(isPublic.equals("Y")){
                menus = dao.queryJSONArray("select *,true 'disabled' from sys_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }else{
                menus = dao.queryJSONArray("select * from sys_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }
        }

        JSONArray menusTree = TreeUtils.commonTree(menus);

        //defaultCheckedKeys
        List<String> defaultCheckedKeys = dao.queryListValue("select menu_id from sys_role_menus where role_id=?",String.class,roleId);

        JSONObject rs = new JSONObject();
        rs.put("data",menusTree);
        rs.put("defaultCheckedKeys",defaultCheckedKeys);
        rs.put("isPublic","Y".equals(isPublic));

        return rs;
    }

    @AutoCodeQuery(value = "appRoleMenus", description = "查询组织角色授权的菜单信息")
    public JSONObject appRoleMenus(JSONObject param){
        String orgCode = UserThreadLocalUtils.getOrgCode();
        String roleId = param.getString("roleId");

        //判定一个角色是否为公共角色
        String isPublic = dao.queryValue("select is_public from sys_roles where id=?",String.class,roleId);

        //获取菜单信息
        List<String> menuIds = dao.queryListValue("select menu_id from app_organ_menu where org_code=?",String.class,orgCode);
        if (!menuIds.isEmpty()){
            String parentSql = "select distinct parent_id from app_menus where id in (?)  or id in (select parent_id from app_menus t2 where t2.id in (?))";
            List<String> parentIds = dao.queryListValue(parentSql,String.class,menuIds,menuIds);
            menuIds.addAll(parentIds);
        }

        JSONArray menus = new JSONArray();
        if (!menuIds.isEmpty()) {
            if(isPublic.equals("Y")){
                menus = dao.queryJSONArray("select *,true 'disabled' from app_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }else{
                menus = dao.queryJSONArray("select * from app_menus where id in (?)  order by menu_type,sort_no ",menuIds);
            }
        }

        JSONArray menusTree = TreeUtils.commonTree(menus);

        //defaultCheckedKeys
        List<String> defaultCheckedKeys = dao.queryListValue("select menu_id from app_role_menus where role_id=?",String.class,roleId);

        JSONObject rs = new JSONObject();
        rs.put("data",menusTree);
        rs.put("defaultCheckedKeys",defaultCheckedKeys);
        rs.put("isPublic","Y".equals(isPublic));

        return rs;
    }

    @AutoCodeQuery(value = "roleUsers", description = "查询角色授权的用户信息")
    public JSONObject roleUsers(JSONObject param){
        JSONObject pagingData = param.getJSONObject("pagingData");
        JSONObject operData = param.getJSONObject("operData");
        SqlWrapperBuilder swb = new SqlWrapperBuilder("sys_users t1,sys_role_users t2");
        swb.selectColumn("t2.*,t1.fullname,t1.email,t1.phone,t1.status");
        swb.where("t1.username=t2.username and t2.org_code=?",UserThreadLocalUtils.getOrgCode());
        swb.eq("t2.role_id",operData.getString("roleId"));
        String keyWord = operData.getString("keyWord");
        if(StrUtil.isNotBlank(keyWord)){
            String lk ="%"+keyWord.trim()+"%";
            swb.where("(t1.fullname like ? or t1.email like ? or t1.phone like ?)",lk,lk,lk);
        }
        swb.orderBy("t1.username");

        SqlWrapper countSqlWrapper = swb.countSqlWrapper();
        dao.pageInfo(pagingData,countSqlWrapper.getSql(),countSqlWrapper.getParams().toArray());
        SqlWrapper sqlWrapper = swb.sqlWrapper();
        JSONArray data = dao.queryJSONArrayByPage(sqlWrapper.getSql(),pagingData,sqlWrapper.getParams().toArray());
        JSONObject rs = new JSONObject();
        rs.put("pagingData",pagingData);
        rs.put("data",data);
        return rs;
    }

    @AutoCodeQuery(value = "queryNotInRoleUser", description = "查询该角色未授权的用户列表，分页查询")
    public JSONObject queryNotInRoleUser(JSONObject param){
        JSONObject pagingData = param.getJSONObject("pagingData");
        JSONObject operData = param.getJSONObject("operData");

        String roleId = operData.getString("roleId");
        String orgCode = UserThreadLocalUtils.getOrgCode();

        SqlWrapperBuilder swb = new SqlWrapperBuilder("sys_users t1,sys_organ_users t2");
        swb.selectColumn("t1.*");
        swb.where("t1.username=t2.username and t2.org_code=? and not exists(select 1 from sys_role_users t3 where t2.username=t3.username and t3.role_id=? and t3.org_code=?)",orgCode,roleId,orgCode);
        String keyWord = operData.getString("keyWord");
        if(StrUtil.isNotBlank(keyWord)){
            String lk = "%"+keyWord+"%";
            swb.where("t1.username like ? or t1.fullname like ?",lk,lk);
        }
        SqlWrapper countSqlWrapper = swb.countSqlWrapper();
        SqlWrapper sqlWrapper = swb.sqlWrapper();
        dao.pageInfo(pagingData,countSqlWrapper.getSql(),countSqlWrapper.getParams().toArray());
        JSONArray data = dao.queryJSONArrayByPage(sqlWrapper.getSql(),pagingData,sqlWrapper.getParams().toArray());
        JSONObject rs = new JSONObject();
        rs.put("pagingData",pagingData);
        rs.put("data",data);
        return rs;
    }

    @AutoCodeQuery(value = "defaultRole", description = "查询默认的角色ID")
    public List<String> defaultRole(JSONObject param){
        String orgCode = param.getString("orgCode");
        //查询默认角色
        return dao.queryListValue("select id from sys_roles where is_default='Y' and (org_code=? or is_public='Y')",String.class,orgCode);
    }

}
